<template>
  <div>
    <div style="display: flex; justify-content: space-between;">
      <el-button size="medium" type="primary" plain @click="add"
        >新增客户信息</el-button
      >
      <div>
        <el-input
          style="width: 250px;"
          v-model="input"
          placeholder="输入姓名,手机号,身份证进行搜索"
        ></el-input>
        <!-- 搜索 -->
        <el-button
          icon="el-icon-search"
          circle
          style="margin-left: 20px;"
          @click="likeEmployee()"
        ></el-button>
      </div>
    </div>

    <div class="goods-table">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
        style="width: 100%;"
      >
        <el-table-column prop="i" label=" " fit fixed> </el-table-column>
        <el-table-column prop="salesmanId" label="客户id" fit width="80">
        </el-table-column>
        <el-table-column prop="clientsId" label="业务员id" fit width="80">
        </el-table-column>
        <el-table-column prop="name" label="客户姓名" fit width="80">
        </el-table-column>
        <el-table-column prop="sex" label="性别" fit width="60">
        </el-table-column>
        <!-- <el-table-column
          prop="employeeBirthday"
          label="出生日期"
          fit
          width="100"
        >
          <template slot-scope="scope">
            {{ formatDate(scope.row.employeeBirthday) }}
          </template>
        </el-table-column> -->
        <el-table-column prop="age" label="年龄" fit width="60">
        </el-table-column>
        <el-table-column prop="mail" label="邮箱" fit width="180">
        </el-table-column>
        <el-table-column prop="phone" label="手机号" fit width="120">
        </el-table-column>
        <el-table-column prop="company" label="公司名称" fit width="120">
        </el-table-column>
        <el-table-column prop="address" label="地址" fit width="120">
        </el-table-column>
        <el-table-column prop="times" label="次数" fit width="120">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" fit width="100">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" fit width="100">
          <template slot-scope="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>

        <!-- 进行中 未开始 已结束 -->
        <el-table-column prop="saleState" label="状态" fit width="100">
          <template slot-scope="scope">
            <el-tag type="success"></el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="操作" width="350" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="Employeeupda(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              v-if="roleType"
              size="mini"
              type="primary"
              @click="applyUpdateEmployee(scope.row.id)"
              >交流记录</el-button
            >
            <el-button
              v-if="roleType"
              size="mini"
              type="primary"
              @click="applyUpdateEmployee(scope.row.id)"
              >订单信息</el-button
            >
            <el-button
              v-if="roleType"
              size="mini"
              type="danger"
              @click="deleteGoods(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 交流记录显示 -->
    <el-dialog
      style="margin-top:0"
      :visible.sync="addFromDialog"
      width="60%"
      :show-close="false"
      :title="title"
    >
      <h3>历史交流记录</h3>
      <div style="display: flex;flex-direction: column;">
        <el-tag v-for="init in chatList" style="margin: 10px;width: 300px;"
          >{{ init.name }}-------交流时间：{{ init.date }}</el-tag
        >
      </div>
      <el-form
        :model="addEmployeeForm"
        :inline="true"
        ref="addEmployeeForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <div style="margin-top: 10px;height: 450px;">
          <RichTextEditor
            style="height: 400px;"
            @update-content="updateContent"
            ref="RichTextEditor"
          >
          </RichTextEditor>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          v-if="applyButton == 2"
          @click="UpdateEmployee(2)"
          >申请修改</el-button
        >
        <el-button @click="addFromDialog = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 新增客户信息显示 -->
    <el-dialog
      style="margin-top:0"
      :visible.sync="addFromDialog2"
      width="60%"
      :show-close="false"
      :title="title"
    >
      <el-form
        :model="addEmployeeForm"
        :inline="true"
        ref="addEmployeeForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="客户姓名" prop="name">
          <el-input
            type="text"
            v-model="addEmployeeForm.name"
            placeholder="客户姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <!-- <el-input type="text" v-model="addEmployeeForm.goodsName" placeholder="商品名称" ></el-input> -->
          <el-select v-model="addEmployeeForm.sex" placeholder="性别">
            <el-option
              v-for="item in SexCategory"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input
            type="text"
            v-model="addEmployeeForm.age"
            placeholder="年龄"
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱" prop="mail">
          <el-input
            type="text"
            v-model="addEmployeeForm.mail"
            placeholder="请填写邮箱地址"
          ></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
            type="text"
            v-model="addEmployeeForm.phone"
            placeholder="手机号"
          ></el-input>
        </el-form-item>

        <el-form-item label="客户状态" prop="type">
          <el-select v-model="addEmployeeForm.type" placeholder="客户状态">
            <el-option
              v-for="item in employeeStatusCategory"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="公司名称" prop="company">
          <el-input
            type="text"
            v-model="addEmployeeForm.company"
            placeholder="公司名称"
          ></el-input>
        </el-form-item>

        <el-form-item label="下次约谈时间" prop="remindTime">
          <el-date-picker
            v-model="addEmployeeForm.remindTime"
            type="datetime"
            placeholder="下次约谈提醒时间"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="提醒原因" prop="reason">
          <el-input
            type="text"
            v-model="addEmployeeForm.reason"
            placeholder="提醒原因"
          ></el-input>
        </el-form-item>

        <el-form-item label="地址" prop="employeeStatus">
          <div id="app">
            <el-cascader
              size="large"
              :options="pcaTextArr"
              v-model="selectedOptions"
            >
            </el-cascader>
          </div>
        </el-form-item>

        <el-form-item label="详细地址" prop="address">
          <el-tag
            :key="tag"
            v-for="tag in dynamicTags"
            style="margin-left: 10px;"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button
            style="margin-left: 10px;"
            v-else
            class="button-new-tag"
            size="small"
            @click="showInput"
            >+ 添加详细地址</el-button
          >
        </el-form-item>

        <br />
        <b>
          交流内容
        </b>
        <div style="margin-top: 10px;height: 450px;">
          <RichTextEditor
            style="height: 400px;"
            @update-content="updateContent"
            ref="RichTextEditor"
          >
          </RichTextEditor>
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          v-if="applyButton == 0"
          @click="UpdateEmployee(0)"
          >新 增</el-button
        >
        <el-button
          type="primary"
          v-if="applyButton == 1"
          @click="UpdateEmployee(1)"
          >修 改</el-button
        >
        <el-button
          type="primary"
          v-if="applyButton == 2"
          @click="UpdateEmployee(2)"
          >申请修改</el-button
        >

        <el-button @click="addFromDialog2 = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from "dayjs";

import {
  getGoodsCategory,
  addEmployeeProfile,
  deleteEmployeeProfileById,
  selectEmployeeProfileById,
  UploadFile,
  updateEmployeeProfile,
  updateEmployeeUpdateStatus,
  selectEmployeeProfileByName,
} from "../../api/all";

import { pcaTextArr } from "element-china-area-data";

import { selectAllClients, selectChatByClientId } from "../../api/clients";
import RichTextEditor from "../../components/RichTextEditor.vue";
export default {
  components: {
    RichTextEditor,
  },
  data() {
    return {
      //用户历史交流记录
      chatList: [
        { name: "第五次交流记录", date: "2021-01-05" },
        { name: "第四次交流记录", date: "2021-01-04" },
        { name: "第三次交流记录", date: "2021-01-03" },
        { name: "第二次交流记录", date: "2021-01-02" },
        { name: "第一次交流记录", date: "2021-01-01" },
      ],
      //用户地址标签
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      //省市区
      pcaTextArr,
      selectedOptions: [],
      //搜索框的值
      input: "",
      materialForm: {
        title: "", //标题
        type: 0, //类型
        content: "这是一封离别信", // 内容
        imageUrl: "", // 图片地址
        videoUrl: "", // 视频地址
      },
      // 图片预览
      srcList: [],
      srcList2: [],
      //修改按钮状态
      applyButton: 0, //0是新增 1是修改，2是申请修改
      // 上传图片文件
      selectedFile: null,
      //判断用户点击的是合同还是保密协议
      htdz: "",
      // 合同地址
      imageUrl: "",
      // 保密协议地址
      imageUrl2: "",
      //新增标题
      title: "交流记录",
      roleType: false,
      cover: "cover",
      // 显示表单
      addFromDialog: false,
      addFromDialog2: false,
      addFromDialog3: false,
      // 表格加载
      loading: false,
      //合同到期提醒
      dialogImageUrl: "",
      dialogVisible: false,
      //表格数据
      tableData: [
        {
          salesmanId: "1000",
          times: 1000,
          age: 111,
          sex: 111,
          phone: "111",
          mail: "111",
          company: "111",
          address: "11",
          province: "11",
          city: "111",
          district: "11",
          name: "12131",
          id: "adwaw",
          clientsId: "123122131",
          content: "1231",
          contentHtml: "1231313",
          remindTime: "2021-01-01T02:49:07.000+00:00",
          createTime: "2024-01-26T02:49:07.000+00:00",
          updateTime: "2024-01-26T02:49:10.000+00:00",
        },
      ],
      // 新增员工档案信息
      addEmployeeForm: {
        id: "",
        userId: "",
        name: "",
        sex: "",
        age: "",
        mail: "",
        phone: "",
        type: "",
        company: "",
        province: "",
        city: "",
        district: "",
        address: "",
        content: "",
        interviewType: 1, //提醒类型 1:联系客户 2:合同到期 3:分期付款提醒
        reason: "", //提醒原因
        remindTime: "",
        createTime: "",
        updateTime: "",
      },
      //总数页
      total: 1,
      // 分页大小
      pageSize: 5,
      //记录当前页数
      currentPage: 1,
      //审核通过状态
      applyStatus: false,
      // 商品分类
      SexCategory: [
        { label: "男", value: 0 },
        { label: "女", value: 1 },
      ],
      //在职信息
      employeeStatusCategory: [
        { label: "成交客户", value: 0 },
        { label: "意向客户", value: 1 },
        { label: "潜在客户", value: 2 },
        { label: "失信客户", value: 3 },
      ],
    };
  },
  mounted() {
    let kes = window.sessionStorage.getItem("loginUser");
    let userObject = JSON.parse(kes);
    if (userObject.roleType == "root") {
      this.roleType = true;
    }
    console.log("userObject", userObject.roleType);
    this.getAllGoods();
    // console.log("初始化时间:", dayjs())
  },
  //超级管理员显示功能
  methods: {
    //标签
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 富文本传值
    updateContent(data) {
      this.materialForm.content = data.content;
      this.materialForm.imageUrl = data.imageList;
      console.log("data===>", this.materialForm.content);
    },
    // 格式化时间
    formatDate(date) {
      const d = new Date(date);
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, "0");
      const day = d
        .getDate()
        .toString()
        .padStart(2, "0");
      const hours = d
        .getHours()
        .toString()
        .padStart(2, "0");
      const minutes = d
        .getMinutes()
        .toString()
        .padStart(2, "0");
      const seconds = d
        .getSeconds()
        .toString()
        .padStart(2, "0");
      //   return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      return `${year}-${month}-${day}`;
    },
    startTimeChange(value) {
      this.addEmployeeForm.startTime = dayjs(value).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      console.log("上架时间", dayjs(value).format("YYYY-MM-DD HH:mm:ss"));
    },
    endTimeChange(value) {
      this.addEmployeeForm.endTime = dayjs(value).format("YYYY-MM-DD HH:mm:ss");
      console.log("上架时间", dayjs(value).format("YYYY-MM-DD HH:mm:ss"));
    },
    // 提交新增员工档案信息表单
    submitaddEmployeeForm() {
      let val = this.infoPet();
      if (val == false) {
        return;
      }
      addEmployeeProfile(this.addEmployeeForm).then((data) => {
        if (data.code) {
          this.$message({
            type: "success",
            message: "新增成功",
          });
          this.getAllGoods();
        } else {
          this.$message({
            type: "error",
            message: "新增失败",
          });
        }
      });
      this.addFromDialog = false;
    },
    //校验新增修改申请时的数据
    infoPet() {
      //校验表单数据不能为空，并且提示框提示
      //   if (
      //     this.addEmployeeForm.employeeAge == "" ||
      //     this.addEmployeeForm.employeeContractDate == "" ||
      //     this.addEmployeeForm.employeeContractFile == "" ||
      //     this.addEmployeeForm.employeeEmail == "" ||
      //     this.addEmployeeForm.employeeEntryDate == "" ||
      //     this.addEmployeeForm.employeeIdcard == "" ||
      //     this.addEmployeeForm.employeeLeaveDate == "" ||
      //     this.addEmployeeForm.employeeName == "" ||
      //     this.addEmployeeForm.employeeSecrecyFile == "" ||
      //     this.addEmployeeForm.employeeSecrecyFile == ""
      //   ) {
      //     this.$message({
      //       type: "error",
      //       message: "请填写完整信息",
      //     });
      //     return false;
      //   }
    },
    //新增员工档案信息
    UpdateEmployee() {
      this.addEmployeeForm.province = this.selectedOptions[0];
      this.addEmployeeForm.city = this.selectedOptions[1];
      this.addEmployeeForm.district = this.selectedOptions[2];
      console.log(this.addEmployeeForm);
      console.log(this.materialForm);
      //富文本赋值
      this.addEmployeeForm.content = this.materialForm.content;
      //把数组拆分，拼接成12312321,21313,123123带,号这样拼接
      this.addEmployeeForm.address = this.dynamicTags.join(",");
      console.log(this.selectedOptions);
      this.infoPet();
      updateEmployeeProfile(this.addEmployeeForm).then((data) => {
        if (data.code) {
          this.$message({
            type: "success",
            message: data.data,
          });
          this.getAllGoods();
          this.addFromDialog = false;
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },
    //模糊查询信息
    likeEmployee() {
      selectEmployeeProfileByName(this.input).then((data) => {
        if (data.code) {
          this.tableData = data.data;
        } else {
          this.$message({
            type: "error",
            message: data.message,
          });
        }
      });
    },
    //在职状态显示
    employeeStatuse(i) {
      let val = "";
      if (i == 0) {
        val = "在职";
      }
      if (i == 1) {
        val = "离职";
      }
      return val;
    },
    //性别显示
    employeeSex(i) {
      let val = "";
      if (i == 0) {
        val = "男";
      }
      if (i == 1) {
        val = "女";
      }
      return val;
    },
    //交谈记录
    applyUpdateEmployee(id) {
      this.title = "交流记录";
      this.imgstatus();
      let kes = window.sessionStorage.getItem("loginUser");
      let userObject = JSON.parse(kes);
      //判断是否为超级管理  0是新增 1是修改，2是申请修改
      if (userObject.roleType == "root") {
        this.applyButton = 3;
      } else {
        this.applyButton = 2;
      }
      selectChatByClientId(id).then((data) => {
        console.log(data);
        this.addFromDialog = true;
      });

      // updateEmployeeProfileByAdmin(id,this.applyStatus).then((data) => {
      //   if (data.code) {
      //     this.$message({
      //       type: "success",
      //       message: "操作成功",
      //     });
      //     this.getAllGoods();
      //   } else {
      //     this.$message({
      //       type: "error",
      //       message: data.message,
      //     });
      //   }
      // });
    },

    //编辑客户信息
    Employeeupda(userId) {
      this.title = "编辑客户信息";
      this.imgstatus();
      let kes = window.sessionStorage.getItem("loginUser");
      let userObject = JSON.parse(kes);
      //判断是否为超级管理  0是新增 1是修改，2是申请修改
      if (userObject.roleType == "root") {
        this.applyButton = 1;
      } else {
        this.applyButton = 2;
      }
      selectEmployeeProfileById(userId).then((data) => {
        console.log(userId);
        this.addFromDialog2 = true;
      });
    },
    //上传图片
    selectFile(i) {
      this.htdz = i;
      this.$refs.fileInput.click();
    },
    //上传oss
    handleFileChange(event) {
      this.selectedFile = event.target.files[0];
      if (this.htdz == 1) {
        this.imageUrl = URL.createObjectURL(this.selectedFile);
      }
      if (this.htdz == 2) {
        this.imageUrl2 = URL.createObjectURL(this.selectedFile);
      }
      this.uploadImage();
    },
    //初始化图片
    imgstatus() {
      let url =
        "https://kris-k.oss-cn-hangzhou.aliyuncs.com/kris/c179093a-41b0-4c70-bc1f-6e5973f35c98-jia.png";
      this.imageUrl = url;
      this.imageUrl2 = url;
    },
    //发送上传文件api
    uploadImage() {
      let formData = new FormData();
      formData.append("file", this.selectedFile);
      UploadFile(formData).then((data) => {
        let url = data.data;
        if (this.htdz == 1) {
          this.addEmployeeForm.employeeContractFile = url;
        }
        if (this.htdz == 2) {
          this.addEmployeeForm.employeeSecrecyFile = url;
        }
      });
    },
    //ReviewArchives 审核档案信息
    ReviewArchives(status) {
      updateEmployeeUpdateStatus(this.addEmployeeForm.id, status).then(
        (data) => {
          if (data.code) {
            this.$message({
              type: "success",
              message: "操作成功",
            });
            this.getAllGoods();
            this.addFromDialog = false;
          } else {
            this.$message({
              type: "error",
              message: data.message,
            });
          }
        }
      );
    },
    // 新增员工档案信息按钮
    add() {
      this.imgstatus();
      this.addEmployeeForm = {
        id: "",
        userId: "",
        name: "",
        sex: "",
        age: "",
        mail: "",
        phone: "",
        type: "",
        company: "",
        province: "",
        city: "",
        district: "",
        address: "",
        content: "",
        createTime: "",
        updateTime: "",
      };
      this.title = "新增客户信息";
      // this.addFromDialog = true;
      this.addFromDialog2 = true;

      this.applyButton = 0; //0是新增 1是修改，2是申请修改
      // 获取商品类别
      this.getGoodsCategory();
    },
    // 查询列表
    getAllGoods() {
      this.loading = true;
      // getGoodsList(this.currentPage, this.pageSize)
      selectAllClients(this.currentPage, this.pageSize)
        .then((res) => {
          if (res.code) {
            this.total = res.data.total;
            this.tableData = res.data.clientsVoList;
            //将图片地址放入数组,需要遍历循环加入数组
            // for (let i = 0; i < res.data.employeeProfileVoList.length; i++) {
            //   this.srcList.push(
            //     res.data.employeeProfileVoList[i].employeeContractFile
            //   );
            //   this.srcList2.push(
            //     res.data.employeeProfileVoList[i].employeeSecrecyFile
            //   );
            // }

            console.log(this.srcList2);
          } else {
            this.$message("列表加载错误");
          }
          console.log("获取商品列表");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // pageSize变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getAllGoods();
    },
    // 页码变化
    handleCurrentChange(curPage) {
      this.currentPage = curPage;
      this.getAllGoods();
    },
    //在职状态
    employeeStatuse(i) {
      let val = "";
      if (i == 0) {
        val = "在职";
      }
      if (i == 1) {
        val = "离职";
      }
      return val;
    },

    //职工修改状态 0:已修改(第一次提交) 1:待审核 2:审核通过 3:审核失败
    employeeUpdateStatuse(i) {
      let val = "";
      if (i == 0) {
        val = "已修改";
      } else if (i == 1) {
        val = "待审核";
      } else if (i == 2) {
        val = "审核通过";
      } else if (i == 3) {
        val = "审核失败";
      }
      return val;
    },
    getGoodsCategory() {
      getGoodsCategory().then((res) => {
        this.gooodsCategory = res.data.map((item) => ({
          label: item.name,
          value: item.id,
        }));
        console.log("获取商品类别", res);
      });
    },
    // 删除商品
    deleteGoods(empl) {
      this.$confirm(
        `确定继续删除名为《${empl.employeeName}》的用户吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          deleteEmployeeProfileById(empl.id).then((res) => {
            if (res.code) {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              this.getAllGoods();
            } else {
              this.$message({
                type: "error",
                message: "删除失败!",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 编辑商品
    editGoods() {},
  },
};
</script>

<style scoped>
.page {
  text-align: center;
}

.goods-table {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  margin-top: 10px;
}
.imgUrl {
  width: 100px;
  height: 100px;
  object-fit: cover; /* 保持原始宽高比，填充容器 */
}
.htimg {
  width: 150px;
  height: 150px;
  object-fit: cover; /* 保持原始宽高比，填充容器 */
}
</style>
